import SwiftUI
import Charts

struct StatisticsView: View {
    @StateObject var viewModel = StatisticsViewModel()
    @State private var showingShareSheet = false
    @State private var showingReport = false
    @State private var csvData = ""
    @State private var chartType = 0 // 0: 柱状图, 1: 折线图, 2: 面积图
    
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 15) {
                    // 时间范围选择器
                    Picker("统计范围", selection: $viewModel.selectedPeriod) {
                        Text("日").tag(StatsPeriod.day)
                        Text("周").tag(StatsPeriod.week)
                        Text("月").tag(StatsPeriod.month)
                    }
                    .pickerStyle(.segmented)
                    .padding(.horizontal)
                    
                    // 图表类型选择
                    Picker("图表类型", selection: $chartType) {
                        Text("柱状图").tag(0)
                        Text("折线图").tag(1)
                        Text("面积图").tag(2)
                    }
                    .pickerStyle(.segmented)
                    .padding(.horizontal)
                    
                    // 饮水量汇总卡片
                    WaterSummaryCard(
                        totalAmount: viewModel.getTotalAmount(),
                        dailyAverage: viewModel.getAverageAmount(),
                        achievementRate: viewModel.goalAchievementRate,
                        bottleCount: Int(viewModel.getTotalAmount() / 500) // 假设一瓶水500ml
                    )
                    .padding(.horizontal)
                    
                    // 图表
                    VStack(alignment: .leading) {
                        Text("饮水量趋势")
                            .font(.headline)
                            .padding(.leading)
                        
                        chartView
                            .frame(height: 250)
                            .padding(.horizontal)
                    }
                    
                    // 目标达成趋势
                    VStack(alignment: .leading) {
                        Text("目标达成趋势")
                            .font(.headline)
                            .padding(.leading)
                        
                        goalAchievementChart
                            .frame(height: 150)
                            .padding(.horizontal)
                    }
                    
                    // 统计摘要
                    VStack(alignment: .leading, spacing: 5) {
                        Text("统计摘要")
                            .font(.headline)
                            .padding(.leading)
                        
                        HStack(spacing: 15) {
                            StatCardView(
                                title: "平均饮水量",
                                value: viewModel.getAverageAmount(),
                                unit: "毫升",
                                icon: "drop.fill"
                            )
                            
                            StatCardView(
                                title: "目标达成率",
                                value: String(format: "%.0f%%", viewModel.goalAchievementRate * 100),
                                unit: "",
                                icon: "target"
                            )
                        }
                        .padding(.horizontal)
                        
                        HStack(spacing: 15) {
                            StatCardView(
                                title: "最高饮水日",
                                value: viewModel.getMaxIntakeDay(),
                                unit: "",
                                icon: "crown.fill"
                            )
                            
                            StatCardView(
                                title: "连续达标",
                                value: "\(viewModel.streakDays)",
                                unit: "天",
                                icon: "flame.fill"
                            )
                        }
                        .padding(.horizontal)
                    }
                    
                    // 水分摄入详情按钮
                    Button(action: {
                        showingReport = true
                    }) {
                        HStack {
                            Image(systemName: "doc.text.fill")
                            Text("查看详细饮水报告")
                        }
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .padding()
                        .background(Color.blue)
                        .cornerRadius(10)
                    }
                    .padding(.horizontal)
                    .padding(.top, 5)
                }
                .padding(.vertical)
            }
            .navigationTitle("饮水统计")
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button(action: {
                        csvData = viewModel.exportCSVData()
                        showingShareSheet = true
                    }) {
                        Image(systemName: "square.and.arrow.up")
                    }
                }
            }
            .sheet(isPresented: $showingShareSheet) {
                if #available(iOS 16.0, *) {
                    ShareSheetView(data: csvData)
                } else {
                    Text("分享功能需要iOS 16或更高版本")
                }
            }
            .sheet(isPresented: $showingReport) {
                WaterReportView(viewModel: viewModel)
            }
            .onAppear {
                viewModel.updateData()
            }
        }
    }
    
    // 根据选定的图表类型显示不同的图表
    var chartView: some View {
        Group {
            switch chartType {
            case 0:
                // 柱状图
                Chart {
                    ForEach(viewModel.chartData, id: \.date) { item in
                        BarMark(
                            x: .value("时间", formatDate(item.date, period: viewModel.selectedPeriod)),
                            y: .value("饮水量", item.amount)
                        )
                        .foregroundStyle(Color.blue.gradient)
                    }
                    
                    // 目标线
                    if viewModel.selectedPeriod != .day {
                        RuleMark(y: .value("目标", viewModel.userProfile.goal))
                            .lineStyle(StrokeStyle(lineWidth: 1.5, dash: [5, 5]))
                            .foregroundStyle(Color.red)
                            .annotation(position: .top, alignment: .trailing) {
                                Text("目标")
                                    .font(.caption)
                                    .foregroundColor(.red)
                            }
                    }
                }
                .chartYAxis {
                    AxisMarks(position: .leading)
                }
                
            case 1:
                // 折线图
                Chart {
                    ForEach(viewModel.chartData, id: \.date) { item in
                        LineMark(
                            x: .value("时间", formatDate(item.date, period: viewModel.selectedPeriod)),
                            y: .value("饮水量", item.amount)
                        )
                        .foregroundStyle(Color.blue)
                        .interpolationMethod(.catmullRom) // 平滑曲线
                    }
                    
                    ForEach(viewModel.chartData, id: \.date) { item in
                        PointMark(
                            x: .value("时间", formatDate(item.date, period: viewModel.selectedPeriod)),
                            y: .value("饮水量", item.amount)
                        )
                        .foregroundStyle(Color.blue)
                    }
                    
                    // 目标线
                    if viewModel.selectedPeriod != .day {
                        RuleMark(y: .value("目标", viewModel.userProfile.goal))
                            .lineStyle(StrokeStyle(lineWidth: 1.5, dash: [5, 5]))
                            .foregroundStyle(Color.red)
                            .annotation(position: .top, alignment: .trailing) {
                                Text("目标")
                                    .font(.caption)
                                    .foregroundColor(.red)
                            }
                    }
                }
                .chartYAxis {
                    AxisMarks(position: .leading)
                }
                
            case 2:
                // 面积图
                Chart {
                    ForEach(viewModel.chartData, id: \.date) { item in
                        AreaMark(
                            x: .value("时间", formatDate(item.date, period: viewModel.selectedPeriod)),
                            y: .value("饮水量", item.amount)
                        )
                        .foregroundStyle(
                            LinearGradient(
                                colors: [.blue, .blue.opacity(0.2)],
                                startPoint: .top,
                                endPoint: .bottom
                            )
                        )
                        .interpolationMethod(.catmullRom) // 平滑曲线
                    }
                    
                    // 目标线
                    if viewModel.selectedPeriod != .day {
                        RuleMark(y: .value("目标", viewModel.userProfile.goal))
                            .lineStyle(StrokeStyle(lineWidth: 1.5, dash: [5, 5]))
                            .foregroundStyle(Color.red)
                            .annotation(position: .top, alignment: .trailing) {
                                Text("目标")
                                    .font(.caption)
                                    .foregroundColor(.red)
                            }
                    }
                }
                .chartYAxis {
                    AxisMarks(position: .leading)
                }
                
            default:
                EmptyView()
            }
        }
    }
    
    // 目标达成趋势图表
    var goalAchievementChart: some View {
        Chart {
            ForEach(viewModel.goalAchievementData, id: \.date) { item in
                BarMark(
                    x: .value("日期", formatDate(item.date, period: .week)),
                    y: .value("达成率", item.percentage * 100)
                )
                .foregroundStyle(Color.green.gradient)
            }
            
            // 目标线
            RuleMark(y: .value("目标", 100))
                .lineStyle(StrokeStyle(lineWidth: 1.5, dash: [5, 5]))
                .foregroundStyle(Color.red)
        }
        .chartYAxis {
            AxisMarks(position: .leading, values: [0, 25, 50, 75, 100]) { value in
                AxisGridLine()
                AxisValueLabel("\(value.index * 25)%")
            }
        }
    }
    
    // 根据选定的时间段格式化日期
    private func formatDate(_ date: Date, period: StatsPeriod) -> String {
        let formatter = DateFormatter()
        
        switch period {
        case .day:
            formatter.dateFormat = "HH:00"
        case .week:
            formatter.dateFormat = "E" // 星期几的简写
        case .month:
            formatter.dateFormat = "d" // 日期
        }
        
        return formatter.string(from: date)
    }
}

// 饮水汇总卡片
struct WaterSummaryCard: View {
    var totalAmount: Double
    var dailyAverage: String
    var achievementRate: Double
    var bottleCount: Int
    
    var body: some View {
        VStack(spacing: 15) {
            // 饮水量显示
            HStack(spacing: 20) {
                // 总饮水量
                VStack(spacing: 5) {
                    Text("总饮水量")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                    
                    Text("\(Int(totalAmount))毫升")
                        .font(.title2)
                        .fontWeight(.bold)
                }
                .padding(.horizontal)
                
                Divider()
                    .frame(height: 40)
                
                // 平均每日
                VStack(spacing: 5) {
                    Text("平均每日")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                    
                    Text("\(dailyAverage)毫升")
                        .font(.title2)
                        .fontWeight(.bold)
                }
                .padding(.horizontal)
            }
            
            Divider()
            
            // 水瓶图标表示
            HStack {
                Text("\(bottleCount) 瓶水")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                Spacer()
                
                HStack(spacing: 2) {
                    ForEach(0..<min(bottleCount, 10), id: \.self) { _ in
                        Image(systemName: "drop.fill")
                            .foregroundColor(.blue)
                            .font(.caption)
                    }
                    
                    if bottleCount > 10 {
                        Text("+\(bottleCount - 10)")
                            .font(.caption)
                            .foregroundColor(.blue)
                    }
                }
            }
            
            // 目标达成进度
            HStack {
                Text("目标达成率")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                Spacer()
                
                Text(String(format: "%.0f%%", achievementRate * 100))
                    .font(.subheadline)
                    .fontWeight(.medium)
            }
            
            ProgressView(value: achievementRate)
                .progressViewStyle(LinearProgressViewStyle(tint: Color.blue))
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(15)
    }
}

// 统计卡片视图（增强版）
struct StatCardView: View {
    var title: String
    var value: String
    var unit: String
    var icon: String
    
    var body: some View {
        VStack(alignment: .center, spacing: 10) {
            // 图标
            Image(systemName: icon)
                .font(.title2)
                .foregroundColor(.blue)
            
            // 标题
            Text(title)
                .font(.caption)
                .foregroundColor(.secondary)
            
            // 值
            HStack(alignment: .bottom, spacing: 2) {
                Text(value)
                    .font(.title3)
                    .fontWeight(.bold)
                
                if !unit.isEmpty {
                    Text(unit)
                        .font(.caption)
                        .foregroundColor(.secondary)
                        .padding(.bottom, 2)
                }
            }
        }
        .frame(maxWidth: .infinity)
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(10)
    }
}

// 水分报告详细视图
struct WaterReportView: View {
    @ObservedObject var viewModel: StatisticsViewModel
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 20) {
                    // 主要指标
                    VStack(alignment: .leading, spacing: 10) {
                        Text("饮水状况总结")
                            .font(.headline)
                            .padding(.horizontal)
                        
                        VStack(spacing: 15) {
                            HydrationStatusRow(
                                title: "饮水状况",
                                status: viewModel.getHydrationStatus(),
                                statusColor: viewModel.getHydrationStatusColor()
                            )
                            
                            Divider()
                            
                            HStack {
                                VStack(alignment: .leading) {
                                    Text("累计饮水量")
                                        .font(.subheadline)
                                        .foregroundColor(.secondary)
                                    
                                    Text("\(Int(viewModel.getTotalAmount()))毫升")
                                        .font(.title3)
                                        .fontWeight(.medium)
                                }
                                
                                Spacer()
                                
                                VStack(alignment: .trailing) {
                                    Text("推荐饮水量")
                                        .font(.subheadline)
                                        .foregroundColor(.secondary)
                                    
                                    Text("\(Int(viewModel.getRecommendedAmount()))毫升")
                                        .font(.title3)
                                        .fontWeight(.medium)
                                }
                            }
                            
                            Divider()
                            
                            HStack {
                                VStack(alignment: .leading) {
                                    Text("总饮水次数")
                                        .font(.subheadline)
                                        .foregroundColor(.secondary)
                                    
                                    Text("\(viewModel.getTotalIntakeCount())次")
                                        .font(.title3)
                                        .fontWeight(.medium)
                                }
                                
                                Spacer()
                                
                                VStack(alignment: .trailing) {
                                    Text("平均每次")
                                        .font(.subheadline)
                                        .foregroundColor(.secondary)
                                    
                                    Text("\(viewModel.getAveragePerIntake())毫升")
                                        .font(.title3)
                                        .fontWeight(.medium)
                                }
                            }
                        }
                        .padding()
                        .background(Color(.systemGray6))
                        .cornerRadius(10)
                        .padding(.horizontal)
                    }
                    
                    // 每日饮水量变化趋势图
                    VStack(alignment: .leading, spacing: 10) {
                        Text("近期饮水量趋势")
                            .font(.headline)
                            .padding(.horizontal)
                        
                        Chart {
                            ForEach(viewModel.daysData, id: \.date) { item in
                                LineMark(
                                    x: .value("日期", item.date),
                                    y: .value("饮水量", item.amount)
                                )
                                .foregroundStyle(Color.blue)
                                .symbol(.circle)
                            }
                        }
                        .frame(height: 200)
                        .padding()
                        .background(Color(.systemGray6))
                        .cornerRadius(10)
                        .padding(.horizontal)
                    }
                    
                    // 饮水分布图
                    VStack(alignment: .leading, spacing: 10) {
                        Text("饮水分布")
                            .font(.headline)
                            .padding(.horizontal)
                        
                        VStack(spacing: 15) {
                            // 早中晚分布饼图
                            HStack {
                                ZStack {
                                    Circle()
                                        .trim(from: 0, to: viewModel.getMorningPercentage())
                                        .stroke(Color.orange, lineWidth: 15)
                                        .rotationEffect(.degrees(-90))
                                    
                                    Circle()
                                        .trim(from: viewModel.getMorningPercentage(), 
                                              to: viewModel.getMorningPercentage() + viewModel.getAfternoonPercentage())
                                        .stroke(Color.blue, lineWidth: 15)
                                        .rotationEffect(.degrees(-90))
                                    
                                    Circle()
                                        .trim(from: viewModel.getMorningPercentage() + viewModel.getAfternoonPercentage(), 
                                              to: 1)
                                        .stroke(Color.purple, lineWidth: 15)
                                        .rotationEffect(.degrees(-90))
                                }
                                .frame(width: 100, height: 100)
                                
                                VStack(alignment: .leading, spacing: 8) {
                                    HStack {
                                        Circle()
                                            .fill(Color.orange)
                                            .frame(width: 10, height: 10)
                                        Text("早上 (6-12点)")
                                            .font(.caption)
                                        Spacer()
                                        Text("\(Int(viewModel.getMorningPercentage() * 100))%")
                                            .font(.caption)
                                            .fontWeight(.medium)
                                    }
                                    
                                    HStack {
                                        Circle()
                                            .fill(Color.blue)
                                            .frame(width: 10, height: 10)
                                        Text("下午 (12-18点)")
                                            .font(.caption)
                                        Spacer()
                                        Text("\(Int(viewModel.getAfternoonPercentage() * 100))%")
                                            .font(.caption)
                                            .fontWeight(.medium)
                                    }
                                    
                                    HStack {
                                        Circle()
                                            .fill(Color.purple)
                                            .frame(width: 10, height: 10)
                                        Text("晚上 (18-24点)")
                                            .font(.caption)
                                        Spacer()
                                        Text("\(Int(viewModel.getEveningPercentage() * 100))%")
                                            .font(.caption)
                                            .fontWeight(.medium)
                                    }
                                }
                                .padding(.leading)
                            }
                            
                            Divider()
                            
                            // 最佳饮水时间
                            VStack(alignment: .leading, spacing: 5) {
                                Text("最佳饮水时间")
                                    .font(.subheadline)
                                    .foregroundColor(.secondary)
                                
                                HStack {
                                    Image(systemName: "clock.fill")
                                        .foregroundColor(.blue)
                                    
                                    Text(viewModel.getBestDrinkingTime())
                                        .font(.headline)
                                }
                            }
                        }
                        .padding()
                        .background(Color(.systemGray6))
                        .cornerRadius(10)
                        .padding(.horizontal)
                    }
                    
                    // 健康建议
                    VStack(alignment: .leading, spacing: 10) {
                        Text("个性化建议")
                            .font(.headline)
                            .padding(.horizontal)
                        
                        VStack(alignment: .leading, spacing: 15) {
                            ForEach(viewModel.getHealthSuggestions(), id: \.self) { suggestion in
                                HStack(alignment: .top, spacing: 12) {
                                    Image(systemName: "checkmark.circle.fill")
                                        .foregroundColor(.green)
                                        .frame(width: 20)
                                    
                                    Text(suggestion)
                                        .font(.subheadline)
                                }
                            }
                        }
                        .padding()
                        .background(Color(.systemGray6))
                        .cornerRadius(10)
                        .padding(.horizontal)
                    }
                }
                .padding(.vertical)
            }
            .navigationTitle("饮水报告")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("关闭") {
                        dismiss()
                    }
                }
            }
        }
    }
}

// 水分状态行
struct HydrationStatusRow: View {
    var title: String
    var status: String
    var statusColor: Color
    
    var body: some View {
        HStack {
            Text(title)
                .font(.subheadline)
                .foregroundColor(.secondary)
            
            Spacer()
            
            Text(status)
                .font(.subheadline)
                .foregroundColor(statusColor)
                .padding(.horizontal, 12)
                .padding(.vertical, 4)
                .background(statusColor.opacity(0.2))
                .cornerRadius(8)
        }
    }
}

// 分享表单
struct ShareSheetView: UIViewControllerRepresentable {
    var data: String
    
    func makeUIViewController(context: Context) -> UIActivityViewController {
        let tempDir = FileManager.default.temporaryDirectory
        let fileURL = tempDir.appendingPathComponent("饮水记录.csv")
        
        do {
            try data.write(to: fileURL, atomically: true, encoding: .utf8)
        } catch {
            print("保存CSV文件失败: \(error)")
        }
        
        let activityViewController = UIActivityViewController(
            activityItems: [fileURL],
            applicationActivities: nil
        )
        
        return activityViewController
    }
    
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
} 